package com.web709.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.web709.entity.Article;
import com.web709.mapper.ArticleMapper;
import com.web709.service.ArticleService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Override
    public List<Article> listByPage(Integer page, Integer size, Integer type) {
        Page<Article> pageInfo = new Page<>(page, size);
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Article::getStatus, 1); // 只查询已发布的
        if (type != null) {
            wrapper.eq(Article::getType, type);
        }
        wrapper.orderByDesc(Article::getCreateTime);
        
        Page<Article> result = this.page(pageInfo, wrapper);
        return result.getRecords();
    }

    @Override
    public Article getByIdWithParticipants(Integer id) {
        return this.getById(id);
    }

    @Override
    public List<Article> searchArticles(String keyword, Integer page, Integer size) {
        Page<Article> pageInfo = new Page<>(page, size);
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();

        // 只搜索已发布的文章
        wrapper.eq(Article::getStatus, 1);

        // 如果关键词不为空，则进行模糊搜索
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w
                    .like(Article::getTitle, keyword)   // 标题包含关键词
                    .or()
                    .like(Article::getContent, keyword) // 或内容包含关键词
            );
        }

        // 按创建时间倒序排序
        wrapper.orderByDesc(Article::getCreateTime);

        Page<Article> result = this.page(pageInfo, wrapper);
        return result.getRecords();
    }
} 